<script setup>
import { reactive, ref } from "vue";
import { adminLogin } from "@/apis/admin/user";
import { useRouter } from "vue-router";

const router = useRouter();
/**
 * 获取登陆表单的对象
 */
const loginFormRef = ref();
/**
 * 登陆表单数据
 */
const loginFormData = reactive({
  username: "admin",
  password: "123456",
});

/**
 * 登录校验规则
 */
const loginFormRules = reactive({
  username: [
    { required: true, message: "用户名不能为空", trigger: "blur" },
    { min: 3, max: 25, message: "用户名长度为3~25", trigger: "blur" },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 3, max: 25, message: "密码长度为3~25", trigger: "blur" },
  ],
});

/**
 * 登陆提交函数
 */
const loginFormCommit = async () => {
  console.log(loginFormData);
  await loginFormRef.value.validate((valid) => {
    if (valid) {
      // 发请求
      adminLogin(loginFormData).then((result) => {
        console.log(result);
        sessionStorage.setItem("Authentication", result.data.token);
        router.push("/admin");
      });
    }
  });
};
/**
 * 实现页面跳转
 * @param {*} path
 */
const navigateToPage = (path) => {
  // console.log(path);
  router.push(path);
};
</script>

<template>
  <div class="title">
    <h1>管理员登录</h1>
  </div>
  <el-form
    class="login-form"
    label-width="auto"
    label-position="top"
    :model="loginFormData"
    :rules="loginFormRules"
    ref="loginFormRef"
  >
    <el-form-item label="用户名" prop="username">
      <el-input v-model="loginFormData.username" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="loginFormData.password" />
    </el-form-item>
    <div class="buttons">
      <el-form-item>
        <el-button type="primary" @click="loginFormCommit"> 登录 </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="navigateToPage('/')">
          回到Home
        </el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<style scoped>
.login-form {
  position: fixed;
  left: 50%;
  right: 50%;
  top: 45%;
  width: 450px;

  transform: translate(-50%, -50%);
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.5);
  padding: 40px 80px;
  border-radius: 6px;
}

.el-input,
.el-buttton {
  width: 300px;
}

.title h1 {
  margin-left: 560px;
  margin-top: 100px;
  color: #f56c6c;
}
.buttons {
  display: flex;
  justify-content: space-between;
}
</style>
